package models

import (
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/beego/memcache"
)

type KestrelStat struct {
	Host         string
	CurrentItems string
	TotalItems   string

	ItemsRate string
}

var t int64 = time.Now().Unix()

var statMap = map[string]KestrelStat{}

func GetKestrelStat(ip string) *KestrelStat {

	c, err := memcache.Connect(ip)
	if err != nil {
		return nil
	}

	kestrelStat := KestrelStat{}
	kestrelStat.Host = ip
	stats, _ := c.Stats("")
	if nil != stats {
		lines := strings.Split(string(stats), "\n")
		if lines != nil && len(lines) > 0 {
			for _, line := range lines {
				stat := strings.Split(line, " ")
				if stat != nil && len(stat) > 2 {
					key := stat[1]
					value := stat[2]
					if key == "curr_items" {
						kestrelStat.CurrentItems = value
					} else if key == "total_items" {
						kestrelStat.TotalItems = value
					}
				}
			}
		}
		v, ok := statMap[ip]
		if ok {
			itemNum := getIntValue(kestrelStat.TotalItems) - getIntValue(v.TotalItems) + (getIntValue(kestrelStat.CurrentItems) - getIntValue(v.CurrentItems))
			if time.Now().Unix()-t >= 1 {
				kestrelStat.ItemsRate = fmt.Sprint(itemNum / (time.Now().Unix() - t))
			}
		}
		statMap[ip] = kestrelStat
	}
	return &kestrelStat
}

func getIntValue(value string) int64 {
	intValue, _ := strconv.ParseInt(value, 10, 64)
	return intValue
}

func KestrelStats(ips []string) []KestrelStat {
	statArray := make([]KestrelStat, 0)
	for _, host := range ips {
		kestrelStat := GetKestrelStat(host)
		if kestrelStat != nil {
			statArray = append(statArray, *kestrelStat)
		}
	}
	t = time.Now().Unix()
	return statArray
}
